<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chatroom</title>
</head>
<body>

<div id="board" style="width: 400px; height: 300px;border: #ff0e15 medium solid">
</div>

<form id="form" action="#">
    <label for="typing">输入聊天信息</label>
    <input id="typing" type="text" />
    <input id="_submit" type="button" value="提交" onclick="sendMessage()" />
</form>

<script type="application/javascript" src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script type="application/javascript">
    var socket = io.connect("http://127.0.0.1:8080");

    // 当连接上后，提示用户输入用户名
    socket.on('connect', function (data) {
        var nickname = prompt('What\'s your nickname?');
        socket.emit('join', nickname);
    });

    // 使客户端发送socket链接
    socket.on('message', function (data) {
        // 当收到消息后，插入到消息框中
        insertMsg(data);
    });

    // 点击提交后发送scoket消息
    function sendMessage() {
        var value = document.getElementById('typing').value;
        socket.emit('message',value);
    }

    function insertMsg(data) {
        var board = document.getElementById('board');
        board.appendChild(document.createTextNode(data));
        board.appendChild(document.createElement('br'));
    }
</script>
</body>
</html>